package fastdht

import (
	"net"
)

const (
	maxTableNum    = 159 * 8
	tokenLength    = 2
	nodeContactLen = 26
	nodeIdLen      = 20
)

//***********************************************
//	KRPC 相关的struct
//***********************************************
// 收到的包的结构体
type packetType struct {
	b       []byte
	address *net.UDPAddr
}

//解析收到数据的结构体
type reviceType struct {
	T string       `bencode:"t"`
	Y string       `bencode:"y"`
	Q string       `bencode:"q"`
	E []string     `bencode:"e"`
	A queryType    `bencode:"a"`
	R responseType `bencode:"r"`
	V string       `bencode:"v"`
}

//解析回复的结构体
type responseType struct {
	Id     string `bencode:"id"`
	Values string `bencode:"values"`
	Nodes  string `bencode:"nodes"`
	Token  string `bencode:"token"`
}

//解析请求的结构体
type queryType struct {
	Id       string `bencode:"id"`
	Target   string `bencode:"target"`
	InfoHash string `bencode:"info_hash"`
	Port     int    `bencode:"port"`
	Token    string `bencode:"token"`
}

//***********************************************
//	发送query 请求的结构体
//***********************************************
type queryMessage struct {
	T string                 `bencode:"t"`
	Y string                 `bencode:"y"`
	Q string                 `bencode:"q"`
	A map[string]interface{} `bencode:"a"`
}

//***********************************************
//	发送reply 回复的结构体
//***********************************************
type replyMessage struct {
	T string                 `bencode:"t"`
	Y string                 `bencode:"y"`
	R map[string]interface{} `bencode:"r"`
}
type errorMessage struct {
	T string        `bencode:"t"`
	Y string        `bencode:"y"`
	E []interface{} `bencode:"e"`
}

type DHT struct {
	Ip      string
	Port    int
	Address *net.UDPAddr
	Conn    *net.UDPConn
	NodeId  Id
	Table   table
}
type Node struct {
	nid     Id
	address *net.UDPAddr
	tid     string
}

type table chan interface{}

func newTable(num int) table {
	t := make(table, num)
	return t
}
func (t table) Pop() interface{} {
	return <-t
}
func (t table) Push(a interface{}) {
	t <- a
}
